package cn.signalpha.modules.auth.granter;

import cn.signalpha.common.constant.AppConstant;
import cn.signalpha.core.log.exception.ServiceException;
import cn.signalpha.core.sms.model.SmsCode;
import cn.signalpha.core.tool.utils.ObjectUtil;
import cn.signalpha.modules.auth.dto.UserInfo;
import cn.signalpha.modules.auth.provider.ITokenGranter;
import cn.signalpha.modules.auth.provider.TokenParameter;
import cn.signalpha.modules.com.service.UserService;
import cn.signalpha.modules.resource.builder.sms.SmsBuilder;
import lombok.AllArgsConstructor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.stereotype.Component;

/**
 * MobileTokenGranter
 */
@Component
@AllArgsConstructor
public class MobileTokenGranter implements ITokenGranter {

	public static final String GRANT_TYPE = "mobile";

	private final SmsBuilder smsBuilder;
	private final UserService userService;

	@Override
	public UserInfo grant(TokenParameter tokenParameter) {
		String username = tokenParameter.getArgs().getStr("username");
		String password = tokenParameter.getArgs().getStr("password");
		//测试环境不需要验证码
		ConfigurableEnvironment environment = new StandardEnvironment();
		String activeProfiles = environment.getActiveProfiles()[0];
		if(activeProfiles.equals(AppConstant.PROD_CODE)){
			if(!smsBuilder.template().validateMessage(new SmsCode().setPhone(username).setValue(password))){
				throw new ServiceException("手机号或验证码错误");
			}
		}

		UserInfo userInfo = userService.userInfo(username);
		if(ObjectUtil.isEmpty(userInfo)){
			throw new ServiceException("手机号或验证码错误");
//			userService.createUser(User.builder().mobile(username).build(), null);
		}
		return userInfo;
	}

}
